package com.topisv.tms.platform.ht;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.log.OrderLog;
import com.topisv.tms.repository.log.OrderLogDao;
import com.topisv.tms.rest.entity.Batch;
import com.topisv.tms.service.AreaService;
import com.topisv.tms.service.CustomerAreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.vo.RestAreaGroupVo;
import com.topisv.tms.utils.vo.RestCustomersAreagroupVo;

/**
 * 批次的Restful API的Controller.
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/api/ht")
public class HTRestController {

	@Autowired
	private EdiOrderService ediOrderService;
	
	@Autowired
	private ShopSourceService shopSourceService;
	
	@Autowired
	private CustomersService customerService;
	
	@Autowired
	private AreaService areaService;
	
	@Autowired
	private CustomerAreaGroupService customerAreaGroupService;
	
	@Autowired
	private OrderLogDao orderLogDao;
	
	
	private static final Logger logger = LoggerFactory.getLogger(HTRestController.class);
	

	@RequestMapping(value = "synOrder",method = RequestMethod.POST)
	public void create(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		JSONObject json=null;
		logger.info("禾唐同步订单,客户：" + appsecret + "jsonData=" + data);
		Customers customers =null;
		String areaGroupCode = "";
		try
		{
			json=JSONObject.fromObject(data);
			
			json = json.getJSONObject("orderInfo");
			EdiOrder ediOrder = new EdiOrder();
			ediOrder.setCustomerCode(appkey);
			ediOrder.setErpType("ht");
			String shopId = json.getString("shopId");;
			ShopSource shopSource = null;
			if("123".equals(appsecret))
			{
				shopSource = shopSourceService.findByHtShopId(shopId);
			}
			else
			{
				shopSource = shopSourceService.findByHtShopId(appsecret + shopId);
			}
			
			if(null != shopSource)
			{
				ediOrder.setCustomerCode(shopSource.getCustomerCode());
				ediOrder.setShopCode(shopSource.getShopCode());
				ediOrder.setShopna(shopSource.getShopName());
				customers = customerService.findByCustomerCode(shopSource.getCustomerCode());
				if(null != customers)
				{
					RestCustomersAreagroupVo  vo =customerAreaGroupService.getRestCustomersAreagroupVo(customers.getCustomerCode());// HttpPost.getRestCustomersAreagroupVo(customers);
					if(null != vo)
					{
						Area area = areaService.findByAreaName(json.getString("consigneeProvince"));
						if(null != area)
						{
							List<RestAreaGroupVo> restAreaGroupVo = vo.getRestAreaGroupDtos();
							for(RestAreaGroupVo ragVo : restAreaGroupVo)
							{
								String areaCodes = ragVo.getAreaCodes();
								if(areaCodes != null && areaCodes.indexOf(area.getAreaCode()) != -1)
								{
									areaGroupCode = ragVo.getAreagroupCode();
									break;
								}
							}
							if(!"".equals(areaGroupCode))
							{
								ediOrder.setAreaGroupCode(areaGroupCode);
								ediOrder.setProvco(area.getAreaCode());
							}
							else
							{
								map.put("state", "false");
								map.put("reason", "省份不在服务范围");
							}
							
						}
						else
						{
							map.put("state", "false");
							map.put("reason", "找不到省份区域");
						}
					}
					else
					{
						map.put("state", "false");
						map.put("reason", "找不到覆盖区域信息");
					}
				}
				else
				{
					map.put("state", "false");
					map.put("reason", "找不到客户信息");
				}
				
			}
			else
			{
				map.put("state", "false");
				map.put("reason", "找不到店铺");
			}
			ediOrder.setIsInvoice(json.getBoolean("hasInvoice"));
			if(ediOrder.getIsInvoice() && "no".equals(shopSource.getBillNo()))
			{
				map.put("state", "false");
				map.put("reason", "要发票订单");
			}
			if("2".equals(json.getString("payType")))
			{
				ediOrder.setIsTopay(true);
				if("no".equals(shopSource.getPayAfter()))
				{
					map.put("state", "false");
					map.put("reason", "货到付款不处理");
				}
			}
			else if("1".equals(json.getString("payType")))
			{
				ediOrder.setIsTopay(false);
			}
			if(null != map.get("state")  && !"".equals(map.get("state")))
			{
				try {
					objectMapper.writeValue(response.getWriter(), map);
				} catch (Exception e1) {
					logger.info("保存失败:" + map.get("state") + "--" + map.get("reason"));
				}
				return;
			}
			ediOrder.setShopId(shopId);
			//ediOrder.setOrdeno(json.getString("outerCode"));
			ediOrder.setCustomerOrdeno(json.getString("orderCode"));
			ediOrder.setFromno(json.getString("outerCode"));
			ediOrder.setCacode(json.getString("logisticCode"));
			ediOrder.setOldCacode(json.getString("logisticCode"));
			ediOrder.setCrtime(new Date());
			ediOrder.setOrderStatus(json.getString("orderStatus"));
			try {
				ediOrder.setBunick(json.getString("buyerNick"));
			} catch (Exception e3) {
			}
			ediOrder.setCustna(json.getString("buyerName"));
			ediOrder.setRecena(json.getString("consigneeUser"));
			ediOrder.setPostco(json.getString("consigneeZip"));
			try {
				ediOrder.setTeleph(json.getString("consigneePhone"));
			} catch (Exception e2) {
				ediOrder.setTeleph("");
			}
			try {
				ediOrder.setMobile(json.getString("consigneeMobile"));
			} catch (Exception e2) {
				ediOrder.setMobile("");
			}
			String sellerMemo = json.getString("sellerMemo");
			if("HN".equals(sellerMemo) || "HD".equals(sellerMemo) || "HB".equals(sellerMemo))
			{
				areaGroupCode = sellerMemo;
				ediOrder.setAreaGroupCode(sellerMemo);
			}
			ediOrder.setProvna(json.getString("consigneeProvince"));
			ediOrder.setCityna(json.getString("consigneeCity"));
			try {
				ediOrder.setDistna(json.getString("consigneeDistrict"));
			} catch (Exception e) {
				ediOrder.setDistna("");
			}
			ediOrder.setAddres(ediOrder.getProvna() + ediOrder.getCityna() + ediOrder.getDistna() + json.getString("consigneeAddress"));
			//ediOrder.setSememo(json.getString("sellerMemo"));
			//ediOrder.setBumemo(json.getString("buyerMemo"));
			ediOrder.setStatus("pending");
			ediOrder.setActuallyPaid(Double.parseDouble(json.getString("payment")));
			
			List<EdiOrderItem> item = new ArrayList<EdiOrderItem>();
			JSONArray jsonArray = json.getJSONArray("goodsInfo");
			int sku_num = 0;
			Map<String,EdiOrderItem> itemMap = new HashMap<String,EdiOrderItem>();
			if(null != jsonArray)
			{
				for(int i=0; i<jsonArray.size(); i++)
				{
					JSONObject jsonObject = (JSONObject)jsonArray.opt(i);
					EdiOrderItem ediOrderItemHT = new EdiOrderItem();
					ediOrderItemHT.setOrdeno(json.getString("outerCode"));
					ediOrderItemHT.setSku(jsonObject.getString("barcode").trim());
					ediOrderItemHT.setNam(jsonObject.getString("goodsName"));
					ediOrderItemHT.setQty(jsonObject.getInt("goodsNum"));
					ediOrderItemHT.setCrtime(new Date());
					ediOrderItemHT.setPri(Double.parseDouble(jsonObject.getString("salePrice")));
					ediOrderItemHT.setPay(Double.parseDouble(jsonObject.getString("payment")));
					ediOrderItemHT.setCustomerCode(ediOrder.getCustomerCode());
					EdiOrderItem tmp = itemMap.get(ediOrderItemHT.getSku());
					if(tmp == null)
					{
						if(ediOrderItemHT.getQty() > 0)
						{
							itemMap.put(ediOrderItemHT.getSku(), ediOrderItemHT);
							//item.add(ediOrderItemHT);
							sku_num += jsonObject.getInt("goodsNum");
						}
					}
					else
					{
						if(ediOrderItemHT.getQty() > 0)
						{
							tmp.setQty(tmp.getQty()+ediOrderItemHT.getQty());
							sku_num += jsonObject.getInt("goodsNum");
						}
					}
					
					
				}
			}
			
			JSONArray jsonArray2 = json.getJSONArray("packageGoodsInfo");
			if(null != jsonArray2)
			{
				for(int i=0; i<jsonArray2.size(); i++)
				{
					JSONObject jsonObject = (JSONObject)jsonArray2.opt(i);
					//int packageNum = jsonObject.getInt("packageNum");
					JSONArray jsonArray3 = jsonObject.getJSONArray("detailList");
					for(int j=0; j<jsonArray3.size(); j++)
					{
						JSONObject jsonObject2 = (JSONObject)jsonArray3.opt(j);
						//sku_num += jsonObject2.getInt("goodsNum");
						EdiOrderItem ediOrderItemHT = new EdiOrderItem();
						ediOrderItemHT.setOrdeno(json.getString("outerCode"));
						ediOrderItemHT.setSku(jsonObject2.getString("barcode").trim());
						ediOrderItemHT.setNam("");
						ediOrderItemHT.setQty(jsonObject2.getInt("goodsNum"));
						ediOrderItemHT.setCustomerCode(ediOrder.getCustomerCode());
						EdiOrderItem tmp = itemMap.get(ediOrderItemHT.getSku());
						if(tmp == null)
						{
							if(ediOrderItemHT.getQty() > 0)
							{
								itemMap.put(ediOrderItemHT.getSku(), ediOrderItemHT);
								//item.add(ediOrderItemHT);
								sku_num += jsonObject2.getInt("goodsNum");
							}
						}
						else
						{
							if(ediOrderItemHT.getQty() > 0)
							{
								tmp.setQty(tmp.getQty()+ediOrderItemHT.getQty());
								sku_num += jsonObject2.getInt("goodsNum");
							}
						}
						//item.add(ediOrderItemHT);
					}
					
				}
			}
			for(String key:itemMap.keySet())
			{
				item.add(itemMap.get(key));
			}
			if(sku_num > 1)
			{
				ediOrder.setOrderType("multiple");
			}
			else if(sku_num == 1)
			{
				ediOrder.setOrderType("single");
				
			}
			ediOrder.setOrderStatus("ok");
			map.put("state", "true");
			map.put("reason", "接收成功");
			ediOrder.setSkuQty(sku_num);
			ediOrder.setSkulst(item);
			ediOrder.setAdtime(TimeUtil.getDateMMSS(json.getString("createTime")));
			ediOrder.setPatime(TimeUtil.getDateMMSS(json.getString("createTime")));
			String expressCode = ediOrder.getCacode();
			String expressCodes = shopSource.getExpressCodes();
			if(null != expressCodes && !"".equals(expressCodes))
			{
				if(expressCodes.indexOf(expressCode) == -1)
				{
					ediOrder.setOrderStatus("no");
					map.put("state", "false");
					map.put("reason", "非合作快递公司订单");
				}
			}
			/*else
			{
				ediOrder.setOrderStatus("no");
				map.put("state", "false");
				map.put("reason", "没有配置合作快递公司");
			}*/
			/*if(!"YTO".equals(ediOrder.getCacode()) && !"LIB".equals(ediOrder.getCustomerCode()))
			{
				ediOrder.setOrderStatus("no");
				map.put("state", "false");
				map.put("reason", "非圆通订单");
			}*/
			if("single".equals(shopSource.getOrderType()) && sku_num == 1)
			{
				ediOrder.setOrderStatus("no");
				map.put("state", "false");
				map.put("reason", "单件订单不处理");
			}
			if("multiple".equals(shopSource.getOrderType()) && sku_num > 1)
			{
				ediOrder.setOrderStatus("no");
				map.put("state", "false");
				map.put("reason", "多件订单不处理");
			}
			
			try {
				
				ediOrder=ediOrderService.saveEdiOrderPlat(ediOrder);
				if("cancel".equals(ediOrder.getStatus())||"no".equals(ediOrder.getOrderStatus())||"repeat".equals(ediOrder.getStatus())){
					map.put("state", "false");
					map.put("reason", ediOrder.getMessage());
				}
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				map.put("state", "false");
				map.put("reason", "保存失败");
				logger.error("保存订单失败", e1);
			}
			
		}
		catch(Exception e)
		{
			map.put("state", "false");
			map.put("reason", "接收失败");
			logger.error("json格式错误==" , e);
		}
		try {
			objectMapper.writeValue(response.getWriter(), map);
			logger.info("返回结果:" + map.get("state") + "--" + map.get("reason"));
		} catch (Exception e1) {
		}
		
	}
	@RequestMapping(value = "synGoods",method = RequestMethod.POST)
	public void synGoods(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		Batch batch = null;
		logger.info("禾唐同步商品jsonData=" + data);
		JSONObject json=null;
		try
		{
			logger.info("禾唐同步商品jsonData=" + data);
			
			json=JSONObject.fromObject(data);
			
			json = json.getJSONObject("orderInfo");
			
			map.put("state", "true");
			map.put("reason", "接收成功");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
		}
		catch(Exception e)
		{
			map.put("state", "true");
			map.put("reason", "接收成功");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			return;
		}
		
	}
	
	@RequestMapping(value = "cancelOrder",method = RequestMethod.POST)
	public void cancelOrder(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		Batch batch = null;
		try
		{
			logger.info("禾唐取消订单jsonData=" + data);
			map.put("state", "true");
			map.put("reason", "接收成功");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
		}
		catch(Exception e)
		{
			map.put("state", "true");
			map.put("reason", "接收成功");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			return;
		}
		
	}

}
